import store from '@/store'
const messageGroups = {}

export const addMessages = (messages, groupId) => {
  if (!messages.length) return
  const messageList= messageGroups[groupId] || uni.getStorageSync(`${store.state.vuex_userInfo.id}_${groupId}`) || []
  const firstMessage = messageList[0]
  if (!firstMessage) {
    messageList.unshift(...messages)
    uni.setStorageSync(`${store.state.vuex_userInfo.id}_${groupId}`, messageList)
    return
  }
  if (firstMessage.id >= messages[0].id) {
    // 历史覆盖
    return
  }

  const findex = messages.findIndex(s => s.id === firstMessage.id)
  if (findex > -1) {
    messageList.unshift(...messages.slice(0, findex))
  } else { // 插入到最前面
    messageList.unshift(...messages)
  }
  uni.setStorageSync(`${store.state.vuex_userInfo.id}_${groupId}`, messageList)
}

export const putMessage = (messages, groupId) => {
  if (!messages.length) return
  const messageList= messageGroups[groupId] || uni.getStorageSync(`${store.state.vuex_userInfo.id}_${groupId}`) || []
  const lastMessage = messageList[messageList.length - 1]
  if (!lastMessage) {
    messageList.push(...messages)
    uni.setStorageSync(`${store.state.vuex_userInfo.id}_${groupId}`, messageList)
    return
  }
  if (lastMessage.id < messages[messages.length - 1].id) {
    // 历史覆盖
    return
  }

  const findex = messages.findIndex(s => s.id === lastMessage.id)
  if (findex > -1) {
    messageList.push(...messages.slice(findex))
  } else {
    messageList.push(...messages)
  }
  uni.setStorageSync(`${store.state.vuex_userInfo.id}_${groupId}`, messageList)
}

export const getMessageList = ({
  group_id,
  last_id = null,
  limit = 15
}) => {
  // uni.removeStorageSync(`${store.state.vuex_userInfo.id}_${group_id}`)
  // return
  const messageList= uni.getStorageSync(`${store.state.vuex_userInfo.id}_${group_id}`) || []
  if (!messageList.length) return []
  if (!last_id) return messageList.slice(0, limit)
  const index = messageList.findIndex(s => s.id === last_id)
  return messageList.slice(index + 1, index + 1 + limit)
}

export const updateLocalMessage = (message) => {
  const messageList = uni.getStorageSync(`${store.state.vuex_userInfo.id}_${message.group_id}`) || []
  const findMessage = messageList.find(s => s.id === message.id)
  Object.assign(findMessage, message)
  uni.setStorageSync(`${store.state.vuex_userInfo.id}_${message.group_id}`, messageList)
}

export const rollbackMessage = (params) => {
  const messageList= messageGroups[params.group_id] || uni.getStorageSync(`${store.state.vuex_userInfo.id}_${params.group_id}`) || []
  const findMessage = messageList.find(s => s.id === params.id)
  if (findMessage) {
    findMessage.status = 'ROLLBACK'
  }

  const yyMsg = messageList.find(s => s.content.yy?.m_id === params.id)
  if (yyMsg) yyMsg.content.yy.t = '引用已被撤回'
  uni.setStorageSync(`${store.state.vuex_userInfo.id}_${params.group_id}`, messageList)
}
